package com.tour.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.tour.config.ResponseWrapper;
import com.tour.entity.Follow;
import com.tour.entity.Post;
import com.tour.entity.User;
import com.tour.mapper.FollowMapper;
import com.tour.mapper.PostMapper;
import com.tour.mapper.UserMapper;
import com.tour.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lel
 * @since 2020-12-30
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    UserMapper userMapper;
    @Autowired
    PostMapper postMapper;
    @Autowired
    FollowMapper followMapper;

    @Value("${appid}")
    private String appid;

    @Value("${callBack}")
    private String callBack;

    @Value("${scope}")
    private String scope;

    @Value("${appsecret}")
    private String appsecret;

    public ResponseWrapper updatePassword(Integer userId, String newPassword){
        User user = userMapper.selectById(userId);
        user.setUserPassword(newPassword);
        int result = userMapper.updateById(user);
        if (result == 1){
            return ResponseWrapper.markCustom(true,200,"修改密码成功",null);
        }else {
            return ResponseWrapper.markError();
        }
    }

    public ResponseWrapper findUserById(Integer userId){
        if (userId == null){
            return ResponseWrapper.markError();
        }else {
            User user = userMapper.selectById(userId);
            QueryWrapper<Post> postQueryWrapper = new QueryWrapper<>();
            postQueryWrapper.eq("user_id",userId);
            int postCount = postMapper.selectCount(postQueryWrapper);
            QueryWrapper<Follow> followQueryWrapper = new QueryWrapper<>();
            followQueryWrapper.eq("mine_id",userId);
            int myFollowCount = followMapper.selectCount(followQueryWrapper);
            QueryWrapper<Follow> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("follow_id",userId);
            int followMeCount = followMapper.selectCount(queryWrapper);
            ResponseWrapper wrapper = ResponseWrapper.markSuccess(user);
            wrapper.getData().put("data",user);
            wrapper.getData().put("postCount",postCount);
            wrapper.getData().put("myFollowCount",myFollowCount);
            wrapper.getData().put("followMeCount",followMeCount);
            return wrapper;
        }
    }
    public ResponseWrapper addUser(User user){
        if (user == null){
            return ResponseWrapper.markError();
        }else {
            QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("user_name",user.getUserName());
            int result = userMapper.selectCount(userQueryWrapper);
            if (result > 0){
                return ResponseWrapper.markCustom(false,500,"该账号已存在",null);
            }else {
                int i = userMapper.insert(user);
                if (i == 1){
                    return ResponseWrapper.markCustom(true,200,"注册成功",null);
                }else {
                    return ResponseWrapper.markError();
                }
            }
        }
    }
    public ResponseWrapper updateUser(User user){
        if (user == null){
            return ResponseWrapper.markError();
        }else {
            int result = userMapper.updateById(user);
            if (result == 1){
                return ResponseWrapper.markCustom(true,200,"修改成功",null);
            }else {
                return ResponseWrapper.markError();
            }
        }
    }
    public ResponseWrapper findAllUser(String content,Integer pageNum,Integer pageSize){
        Page<User> page = new Page<>(pageNum,pageSize);
        QueryWrapper<User> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.like("name",content);
        IPage<User> iPage =  userMapper.selectPage(page,adminQueryWrapper);
        List list = iPage.getRecords();
        ResponseWrapper wrapper = ResponseWrapper.markSuccess(list);
        wrapper.getData().put("data",list);
        wrapper.getData().put("total",iPage.getTotal());
        wrapper.getData().put("pageSize",iPage.getSize());
        wrapper.getData().put("pageNum",iPage.getCurrent());
        return wrapper;
    }

    public ResponseWrapper delUser(Integer userId){
        if (userId == null){
            return  ResponseWrapper.markError();
        }else {
            int result = userMapper.deleteById(userId);
            if (result == 1){
                return ResponseWrapper.markCustom(true,200,"删除成功",null);
            }else {
                return ResponseWrapper.markError();
            }
        }
    }

    public List<User> findAll(){
        List<User> users = userMapper.selectList(null);
        return users;
    }

    public void excel(HttpServletResponse response)throws IOException {
        //确定编码的格式
        response.setCharacterEncoding("UTF-8");
        //获取导出的数据
        List<User> list = findAll();
        //创建excel文件
        XSSFWorkbook wb = new XSSFWorkbook();
        //创建sheet页
        XSSFSheet sheet = wb.createSheet("学生信息表");
        //创建标题行
        XSSFRow titleRow = sheet.createRow(0);
        titleRow.createCell(0).setCellValue("ID");
        titleRow.createCell(1).setCellValue("姓名");
        titleRow.createCell(2).setCellValue("账号");
        titleRow.createCell(3).setCellValue("密码");
        titleRow.createCell(4).setCellValue("手机号码");
        titleRow.createCell(5).setCellValue("是否启用");
        titleRow.createCell(6).setCellValue("个性签名");
        String result = null;
        //遍历将数据放到excel列中
        for (User user : list) {
            XSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()+1);
            dataRow.createCell(0).setCellValue(user.getUserId());
            dataRow.createCell(1).setCellValue(user.getName());
            dataRow.createCell(2).setCellValue(user.getUserName());
            dataRow.createCell(3).setCellValue(user.getUserPassword());
            dataRow.createCell(4).setCellValue(user.getUserPhone());
            if (user.getUserDeleted() == false){
                result = "已启用";
            }else {
                result = "已禁用";
            }
            dataRow.createCell(5).setCellValue(result);
            dataRow.createCell(6).setCellValue(user.getUserMotto());
        }
            /*   // 设置下载时客户端Excel的名称
            String filename =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + ".xls";
               response.setContentType("application/vnd.ms-excel");
               response.setHeader("Content-disposition", "attachment;filename=" + filename);  */

        // 设置下载时客户端Excel的名称   （上面注释的改进版本，上面的中文不支持）
        response.setContentType("application/octet-stream;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename="
                //该版本为2007-的版本
                + new String("用户名单".getBytes("UTF-8"),"iso-8859-1")
                + ".xlsx");
        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();

    }

    /**
     * @Description:调转第三方接口，授权登录，拿到code
     * @return：返回的第三方登录的完整网址
     */
    public ResponseWrapper wechatlogin(){
        System.out.println(callBack+"   callback");
        String oauthUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+appid
                +"&redirect_uri="+callBack
                + "&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        ResponseWrapper wrapper = ResponseWrapper.markSuccess(oauthUrl);
        wrapper.getData().put("url",oauthUrl);
        return wrapper;

    }
    /**
     * @Description:传入code进行用户信息的获取
     * @return：修改到数据库的操作是否成功
     */
    public ResponseWrapper getUserInfo(String code) throws UnsupportedEncodingException {
        // 拼接网址 code是第一步返回的网址
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid+"&secret=" +appsecret+
                "&code=" +code+
                "&grant_type=authorization_code";
        RestTemplate template = new RestTemplate();
        // 请求url指定的网址
        ResponseEntity<String> responseEntity = template.getForEntity(url,String.class);
        // 将获得的json格式数据转换成map方便存取
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        String jsonString =responseEntity.getBody();
        map = gson.fromJson(jsonString, map.getClass());
        // access_token和openid单独取出来，方便下一步使用
        String access_token=(String) map.get("access_token");
        String openid=(String) map.get("openid");
        // 判断openid是否存在，提前除了解决下面openid不存在一直sql报错
        if (openid == null){
            return ResponseWrapper.markCustom(false,500,"code不能重复使用",null);
        }
        RestTemplate infotemplate = new RestTemplate();
        // 请求指定的网址 access_token是上面获取的access_token，openid也是上面获取的openid，lang是语言有zh_CN 简体，zh_TW 繁体，en 英语可选
        String infourl ="https://api.weixin.qq.com/sns/userinfo?access_token="+access_token+"&openid="+openid+"&lang=zh_CN";
        ResponseEntity<String> inforesponseEntity = infotemplate.getForEntity(infourl,String.class);
        // 解决昵称等中文乱码
        String infojson = new String(inforesponseEntity.getBody().getBytes("ISO-8859-1"),"UTF-8");
        map = gson.fromJson(infojson, map.getClass());
        // 微信昵称
        String nickname=(String) map.get("nickname");
        // 头像图片地址
        String headimgurl=(String) map.get("headimgurl");
        // 将数据存入user对象方便存入数据库操作
        User user = new User();
        user.setName(nickname);
        user.setHesdPortrait(headimgurl);
        user.setOpenid(openid);
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("openid",openid);
        // 判断数据库是否有这个用户
        List<User> list = userMapper.selectList(userQueryWrapper);
        // 如果有这个用户则进行修改操作
        if (list.size() > 0){
            Integer userId = list.get(0).getUserId();
            user.setUserId(userId);
            int result = userMapper.updateById(user);
            if (result == 1){
                ResponseWrapper wrapper =ResponseWrapper.markSuccess(user);
                wrapper.getData().put("userId",userId);
                wrapper.getData().put("access_token",access_token);
                wrapper.getData().put("openid",openid);
                wrapper.getData().put("name",nickname);
                wrapper.getData().put("hesdProtrait",headimgurl);
                return wrapper;

            }else {
                return ResponseWrapper.markError();
            }
        }else {
            // 如果没有这个用户则进行增加操作
            int result = userMapper.insert(user);
            if (result == 1){
                ResponseWrapper wrapper =ResponseWrapper.markSuccess(user);
                QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("openid",openid);
                User users = userMapper.selectOne(queryWrapper);
                wrapper.getData().put("userId",users.getUserId());
                wrapper.getData().put("access_token",access_token);
                wrapper.getData().put("openid",openid);
                wrapper.getData().put("name",nickname);
                wrapper.getData().put("hesdProtrait",headimgurl);
                return wrapper;
            }else {
                return ResponseWrapper.markError();
            }
        }

    }

    public ResponseWrapper istoken(String access_token,String openid){
        String url = "https://api.weixin.qq.com/sns/auth?access_token="+access_token+"&openid="+openid;
        RestTemplate template = new RestTemplate();
        // 请求url指定的网址
        ResponseEntity<String> responseEntity = template.getForEntity(url,String.class);
        // 将获得的json格式数据转换成map方便存取
        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        String jsonString =responseEntity.getBody();
        map = gson.fromJson(jsonString, map.getClass());
        // access_token和openid单独取出来，方便下一步使用
        String errmsg=(String) map.get("errmsg");
        if (errmsg.equals("ok")){
            String istoke = "ture";
            ResponseWrapper wrapper = ResponseWrapper.markCustom(true,200,"token有效",istoke);
            wrapper.getData().put("istoken",istoke);
            return wrapper;
        }else {
            String istoke = "false";
            ResponseWrapper wrapper = ResponseWrapper.markCustom(false,500,"token失效",istoke);
            wrapper.getData().put("istoken",istoke);
            return wrapper;
        }

    }
}
